<template>
  <div class="project-manager">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="项目类型(子)">
          <!-- <el-select v-model="searchForm.typeson" multiple placeholder="请选择">
            <el-option v-for="item in typeSonList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select> -->
          <el-input v-model="searchForm.typeson" placeholder="请输入项目类型(子)" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="项目进度">
          <el-select clearable v-model="searchForm.schedule" placeholder="请选择项目进度" style="width: 150px;">
            <el-option label="未开工" value="0" />
            <el-option label="在建" value="1" />
            <el-option label="主体工程已完工" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.nameSon" placeholder="请输入项目名称" style="width: 200px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-area">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="handleUpdate" :disabled="selectedRows.length !== 1">修改</el-button>
      <el-button type="danger" @click="handleDelete" :disabled="selectedRows.length === 0">删除</el-button>
      <!-- <el-button @click="handleExport">导出</el-button> -->
    </div>

    <!-- 项目列表 -->
    <div class="table-area">
      <el-table v-loading="loading" :data="projectList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="nameson" label="项目名称" />
        <el-table-column prop="typeson" label="项目类型(子)" >
        </el-table-column>
        <el-table-column prop="location" label="建设地点" />
        <el-table-column prop="longitude" label="经度" />
        <el-table-column prop="latitude" label="纬度" />
        <el-table-column prop="startdate" label="建设开始时间" />
        <el-table-column prop="enddate" label="建设结束时间" />
        <el-table-column prop="unit" label="承担单位" />
        <el-table-column prop="projectProgress" label="项目进度">
          <template slot-scope="scope">
            {{scope.row.schedule == 0 ? '未开工' : (scope.row.schedule == 1 ? '在建' : '主体工程已完工')}}
          </template>
        </el-table-column>
        <el-table-column prop="projectType" label="项目类型">
          <template slot-scope="scope">
            {{scope.row.protype == 0 ? '工程' :'非工程'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="handleRemove(scope.row.id)"
              style="color: #f56c6c;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
    </div>

    <!-- 新增/修改弹框 -->
    <el-dialog :title="isEdit ? '修改项目工程信息' : '添加项目工程信息'" :visible.sync="dialogVisible" width="1000px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="nameson">
              <el-input v-model="formData.nameson" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="relation">
              <el-select v-model="formData.relation" placeholder="请选择行政区划">
                <el-option v-for="item in reginList" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目类别" prop="typeson">
              <!-- <el-select v-model="formData.typeson" placeholder="请选择项目类别">
                <el-option label="工程" value="0" />
                <el-option label="非工程" value="1" />
              </el-select> -->
              <el-input v-model="formData.typeson" placeholder="请输入项目类别" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建设地点" prop="location">
              <el-input v-model="formData.location" placeholder="请输入建设地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="建设开始时间" prop="startdate">
              <el-date-picker v-model="formData.startdate" type="date" placeholder="选择日期"
                style="width: 100%;" value-format="yyyy-MM-dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建设结束时间" prop="enddate">
              <el-date-picker v-model="formData.enddate" type="date" placeholder="选择日期"
                style="width: 100%;" value-format="yyyy-MM-dd"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="承担单位" prop="unit">
              <el-input v-model="formData.unit" placeholder="请输入承担单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目建设规模与内容" prop="scale">
              <el-input v-model="formData.scale" placeholder="请输入项目建设规模与内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="批复项目总投资" prop="approvalfund">
              <el-input v-model.number="formData.approvalfund" placeholder="请输入批复项目总投资" >
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拟申请中央资金" prop="applyfund">
              <el-input v-model.number="formData.applyfund" placeholder="请输入拟申请中央资金" >
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="地方拟投入资金" prop="localfund">
              <el-input v-model.number="formData.localfund" placeholder="请输入地方拟投入资金" >
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社会资金" prop="socialfund">
              <el-input v-model.number="formData.socialfund" placeholder="请输入社会资金" >
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="关联水体" prop="waterbody">
              <el-input v-model="formData.waterbody" placeholder="请输入关联水体" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目进度" prop="schedule">
              <el-select v-model="formData.schedule" placeholder="请选择项目进度">
                <el-option label="未开工" value="0" />
                <el-option label="在建" value="1" />
                <el-option label="主体工程已完工" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="protype">
              <el-select v-model="formData.protype" placeholder="请选择项目类型">
                <el-option label="工程" value="0" />
                <el-option label="非工程" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否采取PPP模式" prop="isp">
              <el-select v-model="formData.isp" placeholder="请选择是否采取PPP模式">
                <el-option label="是" value="0" />
                <el-option label="否" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目成熟度分类" prop="maturity">
              <el-input v-model="formData.maturity" placeholder="请输入项目成熟度分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- (0-中央,1-地方,2-中央和地方共同事权,3-企业) -->
            <el-form-item label="项目事权分类" prop="authority">
              <el-select v-model="formData.authority" placeholder="请选择项目事权分类">
                <el-option label="中央" value="0" />
                <el-option label="地方" value="1" />
                <el-option label="中央与地方共同事权" value="2" />
                 <el-option label="企业" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="项目批复文件" prop="approvalFile">
              <el-upload class="upload-demo" :action="uploadUrl" :before-upload="beforeUpload"
                :on-success="onUploadSuccess" :on-error="onUploadError" :show-file-list="true" :file-list="fileList"
                accept=".doc,.docx,.ppt,.pptx,.txt,.pdf" :limit="1" :on-exceed="handleExceed">
                <el-button size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">
                  请上传大小不超过20MB格式为doc/xls/ppt/txt/pdf的文件
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProjectList, getProjectInfo, addProject, editProject, removeProject } from './api/projectManager'
import {
  getRegionSelect,
} from "@/api/dataResources/monitorData/section.js";
export default {
  name: 'ProjectManager',
  data() {
    return {
      typeSonList: [],
      searchForm: {
        typeson: '',
        schedule: '',
        nameson: ''
      },
      projectList: [],
      loading: false,
      selectedRows: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      isEdit: false,
      formData: {
        nameson: '',
        relation: '',
        protype: '',
        location: '',
        longitude: '',
        latitude: '',
        startdate: '',
        enddate: '',
        unit: '',
        scale: '',
        approvalfund: '',
        applyfund: '',
        localfund: '',
        socialfund: '',
        waterbody: '',
        schedule: '',
        isp: '',
        maturity: '',
        authority: '',
        approvalFile: ''
      },
      rules: {
        nameson: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ]
      },
      reginList: [],
      uploadUrl: '/drinkingwater/project/uploadFile',
      fileList: []
    }
  },
  created() {
    this.getRegionSelect()
    this.getProjectData()
  },
  methods: {
    // 获取行政区划下拉选项数据
    getRegionSelect() {
      getRegionSelect().then((response) => {
        console.log(">>>行政区划", response);
        this.reginList = response.rows.map((item) => ({
          value: item.code,
          label: item.name,
        }));
      });
    },
    // 获取项目列表数据
    async getProjectData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const res = await getProjectList(params)
        if (res.code === 200) {
          this.projectList = res.rows
          this.pagination.total = res.total
        }
      } catch (error) {
        console.error('获取项目列表失败:', error)
        this.$message.error('获取项目列表失败')
      } finally {
        this.loading = false
      }
    },

    // 处理搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.getProjectData()
    },

    // 处理重置
    handleReset() {
      this.searchForm = {
        typeson: '',
        schedule: '',
        nameson: ''
      }
      this.getProjectData()
    },

    // 处理新增
    handleAdd() {
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },

    // 处理修改
    async handleEdit(row) {
      this.isEdit = true
      this.resetForm()
      try {
        const res = await getProjectInfo(row.id)
        if (res.code === 200) {
          this.formData = { ...res.data }
          // 如果有附件文件，设置文件列表
          if (this.formData.approvalFile) {
            this.fileList = [{ name: this.formData.approvalFile, url: '' }]
          }
        }
      } catch (error) {
        console.error('获取项目详情失败:', error)
        this.$message.error('获取项目详情失败')
      }
      this.dialogVisible = true
    },

    // 处理批量修改
    handleUpdate() {
      if (this.selectedRows.length === 1) {
        this.handleEdit(this.selectedRows[0])
      }
    },

    // 处理删除
    handleRemove(id) {
      this.$confirm('确定要删除该项目信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await removeProject(id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getProjectData()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除项目失败:', error)
          this.$message.error('删除项目失败')
        }
      })
    },

    // 处理批量删除
    handleDelete() {
      this.$confirm(`确定要删除选中的 ${this.selectedRows.length} 条项目信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedRows.map(row => row.id)
          const res = await removeProject(ids)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getProjectData()
            this.selectedRows = []
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除项目失败:', error)
          this.$message.error('删除项目失败')
        }
      })
    },

    // 处理导出
    async handleExport() {
      try {
        const res = await exportProject(this.searchForm)
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `项目工程信息_${parseTime(new Date(), '{yyyy}{mm}{dd}')}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出项目失败:', error)
        this.$message.error('导出项目失败')
      }
    },

    // 提交表单
    async handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            let res
            if (this.isEdit) {
              res = await editProject(this.formData)
            } else {
              res = await addProject(this.formData)
            }
            if (res.code === 200) {
              this.$message.success(this.isEdit ? '修改成功' : '新增成功')
              this.dialogVisible = false
              this.getProjectData()
            } else {
              this.$message.error(res.msg || (this.isEdit ? '修改失败' : '新增失败'))
            }
          } catch (error) {
            console.error(`${this.isEdit ? '修改' : '新增'}项目失败:`, error)
            this.$message.error(`${this.isEdit ? '修改' : '新增'}项目失败`)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.formData = {
        nameson: '',
        relation: '',
        protype: '',
        location: '',
        longitude: '',
        latitude: '',
        startdate: '',
        enddate: '',
        unit: '',
        scale: '',
        approvalfund: '',
        applyfund: '',
        localfund: '',
        socialfund: '',
        waterbody: '',
        schedule: '',
        isp: '',
        maturity: '',
        authority: '',
        approvalFile: ''
      }
      this.fileList = []
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },

    // 处理表格选择变化
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.getProjectData()
    },

    // 处理当前页码变化
    handleCurrentChange(current) {
      this.pagination.pageNum = current
      this.getProjectData()
    },

    // 上传文件前的校验
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return false
      }
      return true
    },

    // 上传文件成功处理
    onUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.formData.approvalFile = response.data.fileName
        this.$message.success('文件上传成功')
      } else {
        this.$message.error(response.msg || '文件上传失败')
      }
    },

    // 上传文件失败处理
    onUploadError(error, file, fileList) {
      this.$message.error('文件上传失败')
    },

    // 处理文件超出数量限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制只能上传 1 个文件`)
    }
  }
}
</script>

<style scoped>
.project-manager {
  padding: 20px;
}

.search-area {
  /* margin-bottom: 20px; */
}

.action-area {
  /* margin-bottom: 20px; */
}

.action-area .el-button {
  /* margin-right: 10px; */
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  text-align: right;
}

.el-upload {
  width: 100%;
}
</style>